package online.chazi.bootplus.metrics.web.adapter;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 说明：统计所有入站的Http请求数量(包括成功、失败和非法的)
 * 使用方法：
 * 创建配置及自定义mvc配置
 * @Configuration
 * class MvcConfig implements WebMvcConfigurer {
 *     @Override
 *     public void addInterceptors(InterceptorRegistry registry) {
 *         registry.addInterceptor(new SimpleCounterAdapter());
 *     }
 * }
 * Created by 叉子同学 on 2020-04-14 15:48
 */
public class SimpleCounterAdapter extends HandlerInterceptorAdapter {

    private static final Counter COUNTER = Counter.builder("Http请求统计")
            .tag("HttpCount", "HttpCount")
            .description("Http请求统计")
            .register(Metrics.globalRegistry);

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        COUNTER.increment();
    }

}
